<template>
  <a-input-search
    placeholder="搜素成员或部门"
    v-model:value="searchValue"
    :allowClear="true"
    style="margin-bottom: 8px"
  >
  </a-input-search>
  <a-tree
    :checked-keys="checkedKeysLocal"
    :autoExpandParent="autoExpandParent"
    @expand="onExpand"
    :expandedKeys="expandedKeys"
    v-if="treeList.length>0"
    :tree-data="treeList"
    checkable
    show-icon
    @check="onCheck"
    :fieldNames=" {children:'children', title:'name', key:'id' } "
  >
    <template #icon="{ type}">
      <template v-if="type == 0">
        <folder-outlined/>
      </template>
      <template v-else>
        <user-outlined/>
      </template>
    </template>
    <template #title="{ name }">
        <span v-if="name.indexOf(searchValue) > -1">
          {{ name.substr(0, name.indexOf(searchValue)) }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
        </span>
      <span v-else>{{ name }}</span>
    </template>
  </a-tree>
</template>

<script lang="ts" setup>
import {onMounted, ref, toRefs, watch} from 'vue';
import {FolderOutlined, UserOutlined} from '@ant-design/icons-vue';
import {getDepartUserTree} from '@/api/base/tag/tag';
import {APP_USER} from '@/enums/cacheEnum';
import {Storage} from '@/utils/Storage';
const tenantid = ref(Storage.Get(APP_USER).tenantid);

defineOptions({
  name: 'treeList',
});
const props = defineProps({
  // 默认选中的节点
  checkedKeys: {
    type: Array,
    default: () => []
  }
})
//取出props
const {checkedKeys} = toRefs(props)
// 部门人员数列表
const treeList = ref([])
const checkedKeysLocal = ref()

// 搜索参数
const searchValue = ref<string>('');
// 定义所要传给父组件的值
const userIds = ref([])
// 传值给父组件
const emit = defineEmits(["getValue", "getkvList",'getmyKVList'])

const autoExpandParent = ref(true)
const  expandedKeys = ref([]) //展开的key
const dataList = []; // 树转list的数据
//点击展开事件
const onExpand = (keys) => {
  console.log("原始",expandedKeys.value)

  console.log('keys',keys)
  // console.log('expandedKeys',expandedKeys);
  expandedKeys.value = keys;
}

const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    dataList.push({ key: node.id, title: node.name,pid: node.parentId });
    if (node.children) {
      generateList(node.children);
    }
  }
};

onMounted(async () => {
  await getTreeList();
  checkedKeysLocal.value = checkedKeys.value
  //console.log('checkedKeysLocal',checkedKeysLocal.value)
  const nodes = getNodesByIds(checkedKeysLocal.value);
  emit("getmyKVList", nodes);
  generateList(treeList.value);  //把树转list
  // console.log('dataList',dataList)

})
watch(checkedKeys, () => {
  checkedKeysLocal.value = checkedKeys.value
})

watch(checkedKeysLocal, (newVal) => {
  const nodes = getNodesByIds(newVal);
  emit("getmyKVList", nodes);
});

watch(searchValue, value => {
  if (!value) return autoExpandParent.value = false;
  const expanded = dataList
    .map((item) => {
      if (item.title.indexOf(value) > -1) {
        console.log("item",item)
        return item.pid
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

const getNodesByIds = (ids) => {
  // 使用 map 和 filter 来获取所有有效的节点，并提取 id 和 name
  const nodeList = ids
    .map(id => findNodeById(id))
    .filter(Boolean) // 过滤掉 null 或 undefined 的结果
    .map(node => ({ key: node.id, value: node.name }));

  return nodeList;
};

const findNodeById = (id) => {
  let result = null;

  let searchNode = (node) => {
    if (node.id == id) {
      result = node
    } else if (node.children && node.children.length > 0 && result == null) {
      node.children.forEach(child => {
        return searchNode(child);
      });
    }
  };
  searchNode(treeList.value[0]);
  return result;
};
//
const onCheck = (checkedKeys, e) => {
  const list = e.checkedNodes
    .filter(node => node.type === 1)
    .map(node => {
      return {key: node.id, value: node.name};
    });

  userIds.value = list.map(item => item.key);
  emit("getValue", userIds.value);
  emit("getkvList", list);
};


// 递归调用
const getKeyList = (value, tree, keyList) => {
  // debugger
  searchValue.value = value;
  // 遍历同一级的树
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    // 如果该节点存在value值则push
    if (node.name.indexOf(value) != -1) {
      keyList.push(node)
    }
    //如果拥有孩子继续遍历
    if (node.children) {
      getKeyList(value, node.children, keyList)
    }
  }
  // 因为是引用类型，所以每次递归操作的都是同一个数组
  return keyList
}

// 查询部门人员树
const getTreeList = async () => {
  const res = await getDepartUserTree({tenantId: tenantid.value})
  if (res.code == 0) {
    treeList.value = res.data
  }
}
</script>
